﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            UserAddDemo();

            //UserGetDemo();

            //SearchDemo();
            //DetectDemo();

            //UserUpdateDemo();
            //MultiSearchDemo();
            Console.ReadLine();
        }

        /// <summary>
        /// 人脸注册
        /// </summary>
        public static void UserAddDemo()
        {
            var client = new FaceClient();

            // 读图片转为Base64String
            var image = ImageToBase64(@"C:\Users\zjx\Desktop\ss\TIM截图20190716162433.jpg");

            var groupId = "group1";
            var userId = "user3";
            var result = client.UserAdd(image, groupId, userId, userId);
            Console.WriteLine(result);
        }

        /// <summary>
        /// 人脸更新
        /// </summary>
        public static void UserUpdateDemo()
        {
            var client = new FaceClient();

            // 读图片转为Base64String
            var image = ImageToBase64(@"C:\Users\zjx\Desktop\ss\TIM截图20190716163400.png");

            var groupId = "group1";

            var userId = "user2";

            // 带参数调用人脸更新
            var result = client.UserUpdate(image, groupId, userId, userId);
            Console.WriteLine(result);
        }

        /// <summary>
        /// 用户信息查询
        /// </summary>
        public static void UserGetDemo()
        {
            var client = new FaceClient();

            var userId = "user1";

            var groupId = "group1";

            // 调用用户信息查询，可能会抛出网络等异常，请使用try/catch捕获
            var result = client.UserGet(groupId, userId);
            Console.WriteLine(result);
        }

        /// <summary>
        /// 人脸检测：检测图片中的人脸并标记出位置信息;
        /// </summary>
        public static void DetectDemo()
        {
            var client = new FaceClient();

            // 读图片转为Base64String
            var image = ImageToBase64(@"C:\Users\zjx\Desktop\ss\6f75beb8-b8df-4b7e-af67-2b3a1975d4e0.jpg");

            // 带参数调用人脸检测
            var result = client.Detect(image);
            Console.WriteLine(result);
        }

        /// <summary>
        /// 1：N人脸搜索：也称为1：N识别，在指定人脸集合中，找到最相似的人脸；
        /// </summary>
        public static void SearchDemo()
        {
            var client = new FaceClient();

            // 读图片转为Base64String
            var image = ImageToBase64(@"C:\Users\zjx\Desktop\ss\6f75beb8-b8df-4b7e-af67-2b3a1975d4e0.jpg");

            var groupIdList = "group1";
            var result = client.Search(image, groupIdList);
            Console.WriteLine(result);
        }

        /// <summary>
        /// 人脸搜索 M:N 识别
        /// </summary>
        public static void MultiSearchDemo()
        {
            var client = new FaceClient();

            string filePath = @"C:\Users\zjx\Desktop\ss\6f75beb8-b8df-4b7e-af67-2b3a1975d4e0.jpg";

            // 读图片转为Base64String
            var image = ImageToBase64(filePath);

            var groupIdList = "group1";

            // 带参数调用人脸搜索 M:N 识别
            var result = client.MultiSearch(image, groupIdList).GetValue("result");
            var face_list = result.Value<Newtonsoft.Json.Linq.JArray>("face_list");
            Image srcImage = Image.FromFile(filePath);
            Image img = srcImage;
            foreach (var item in face_list)
            {
                var location = item.Value<Newtonsoft.Json.Linq.JToken>("location");
                var user_list = item.Value<Newtonsoft.Json.Linq.JArray>("user_list");
                Color color = Color.Red;
                if (user_list != null && user_list.HasValues)
                {
                    color = Color.Blue;
                }

                img = MarkRect(img, (int)location.Value<float>("left"), (int)location.Value<float>("top"), (int)location.Value<float>("width"), (int)location.Value<float>("height"), color);
            }

            if (img != null)
            {
                img.Save(Path.Combine(Path.GetDirectoryName(filePath), "11.jpg"));
            }

            Console.WriteLine(result);
        }

        /// <summary>
        /// 用矩形框标记图片指定区域
        /// </summary>
        /// <param name="image">图片</param>
        /// <param name="startX">矩形框左上角X坐标</param>
        /// <param name="startY">矩形框左上角Y坐标</param>
        /// <param name="width">矩形框宽度</param>
        /// <param name="height">矩形框高度</param>
        /// <returns>标记后的图片</returns>
        private static Image MarkRect(Image image, int startX, int startY, int width, int height, Color color)
        {
            Image clone = (Image)image.Clone();
            Graphics g = Graphics.FromImage(clone);
            try
            {
                Brush brush = new SolidBrush(color);
                Pen pen = new Pen(brush, 2);
                pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
                g.DrawRectangle(pen, new Rectangle(startX, startY, width, height));
                return clone;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                g.Dispose();
            }

            return null;
        }

        /// <summary>
        /// 读图片转为Base64String
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private static string ImageToBase64(string filePath)
        {
            string base64 = string.Empty;

            using (System.Drawing.Bitmap bmp1 = new System.Drawing.Bitmap(filePath))
            {
                using (MemoryStream ms1 = new MemoryStream())
                {
                    bmp1.Save(ms1, System.Drawing.Imaging.ImageFormat.Jpeg);
                    byte[] arr1 = new byte[ms1.Length];
                    ms1.Position = 0;
                    ms1.Read(arr1, 0, (int)ms1.Length);
                    ms1.Close();
                    base64 = Convert.ToBase64String(arr1);  // 检测图片的内容，Base64编码
                }
            }

            return base64;
        }
    }
}
